package com.huan.rss.reader;

import com.huan.rss.buffer.NewBuffer;
import com.huan.rss.writer.NewsWriterTask;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NewsSystem implements Runnable {
    private Logger logger = Logger.getLogger(NewsSystem.class);
    private String sourcePath;//sources.txt中的RSS源的地址
    private String url;
    private ScheduledThreadPoolExecutor executor;//定时线程池
    private NewBuffer buffer;
    public NewsSystem(String url){
        this.url = url;
        executor = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
        buffer = new NewBuffer();
    }

    @Override
    public void run() {
        sourcePath = url;
        //消费任务
        NewsWriterTask task = new NewsWriterTask(buffer);
        Thread t = new Thread(task);
        t.start();
        //读取sources.txt中的RSS源的地址，有几个源，就启动几个生产任务
        Path file = Paths.get(sourcePath);
        try(BufferedReader reader = new BufferedReader(new FileReader(file.toFile()))){
            String line = null;
            while ((line = reader.readLine())!= null){
                String[] strings = line.split(";");
                if (strings.length == 2){
                    String rssName = strings[0];
                    String rssUrl = strings[1];
                    //创建生产者的任务
                    NewsReaderTask task1 = new NewsReaderTask(rssName,rssUrl,buffer);
                    //使用线程池来启动生产者的任务
                    this.executor.scheduleWithFixedDelay(task1,0,10, TimeUnit.MINUTES);
                }
            }
        }catch (Exception e){
            logger.error(e);
        }
    }
}
